import api from '../../api'

const state = {
  token: uni.getStorageSync('token') || '',
  userId: uni.getStorageSync('userId') || '',
  userInfo: uni.getStorageSync('userInfo') || {},
  isLoggedIn: !!uni.getStorageSync('token')
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    state.isLoggedIn = !!token
    uni.setStorageSync('token', token)
  },
  SET_USER_ID(state, userId) {
    state.userId = userId
    uni.setStorageSync('userId', userId)
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    uni.setStorageSync('userInfo', userInfo)
  },
  LOGOUT(state) {
    state.token = ''
    state.userId = ''
    state.userInfo = {}
    state.isLoggedIn = false
    uni.removeStorageSync('token')
    uni.removeStorageSync('userId')
    uni.removeStorageSync('userInfo')
  }
}

const actions = {
  // 微信登录
  async wxLogin({ commit }, { code, userInfo }) {
    try {
      const result = await api.auth.wxLogin({
        code,
        userInfo
      })
      
      console.log('登录响应:', result)
      
      // 处理后端返回的数据
      if (result.token) {
        commit('SET_TOKEN', result.token)
        
        if (result.user && result.user.id) {
          commit('SET_USER_ID', result.user.id)
          commit('SET_USER_INFO', result.user)
        } else {
          commit('SET_USER_INFO', userInfo)
        }
      }
      
      return result
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  },
  
  // 获取用户信息
  async getUserInfo({ commit }) {
    try {
      const result = await api.user.getUserInfo()
      commit('SET_USER_INFO', result)
      return result
    } catch (error) {
      throw error
    }
  },
  
  // 退出登录
  logout({ commit }) {
    commit('LOGOUT')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 